package cn.mall.order.controller;

import cn.hutool.json.JSONObject;
import cn.mall.auth.annotation.MyPermission;
import cn.mall.base.constants.BaseConstants;
import cn.mall.base.utils.VideoUtils;
import cn.mall.order.domain.*;
import cn.mall.order.dto.*;
import cn.mall.order.service.IOrderService;
import cn.mall.order.service.impl.OrderDataMonitorService;
import cn.mall.order.query.OrderQuery;
import cn.mall.base.utils.PageList;
import cn.mall.base.utils.AjaxResult;
import cn.mall.order.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/order")
@MyPermission(name = "订单管理")
public class OrderController {
    @Autowired
    public IOrderService orderService;
    
    @Autowired
    private OrderDataMonitorService orderDataMonitorService;
    
    /**
     * 保存和修改公用的
     *
     * @param order 传递的实体
     * @return Ajaxresult转换结果
     */
    @MyPermission(name = "订单的新增/修改")
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Order order) {
        try {
            if (order.getId() != null)
                orderService.update(order);
            else
                orderService.insert(order);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("保存对象失败！" + e.getMessage());
        }
    }

    /**
     * 删除对象信息
     *
     * @param id
     * @return
     */

    @DeleteMapping(value = "/{id}")
    public AjaxResult remove(@PathVariable("id") Long id) {
        try {
            orderService.remove(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("删除对象失败！" + e.getMessage());
        }
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PatchMapping
    public AjaxResult patchRemove(@RequestBody List<Long> ids) {
        try {
            orderService.patchRemove(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("批量删除失败！" + e.getMessage());
        }
    }

    /**
     * 根据Id获取用户
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public AjaxResult loadById(@PathVariable("id") Long id) {
        try {
            Order order = orderService.loadById(id);
            
            // 如果找到订单，添加初始数据信息
            if (order != null) {
                Map<String, Object> orderMap = convertOrderToMap(order);
                enrichOrderWithInitialData(orderMap, order);
                return AjaxResult.me().setResultObj(orderMap);
            }
            
            return AjaxResult.me().setResultObj(order);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("获取一个失败！" + e.getMessage());
        }
    }


    /**
     * 查看所有的员工信息
     *
     * @return
     */
    @GetMapping
    public AjaxResult loadAll() {

        try {
            List<Order> list = orderService.loadAll();
            return AjaxResult.me().setResultObj(list);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("获取所有失败！" + e.getMessage());
        }
    }


    /**
     * 分页查询数据
     *
     * @param query 查询对象
     * @return PageList 分页对象
     */
    @PostMapping
    @MyPermission(name = "订单查询", desc = "订单查询")
    public AjaxResult pageList(@RequestBody OrderQuery query) {
        try {
            // 限制每页大小，避免查询过多数据
            if (query.getPageSize() > 100) {
                query.setPageSize(100L);
            }
            
            PageList<Order> pageList = orderService.pageList(query);
            
            // 处理查询返回结果，添加初始数据信息
            if (pageList != null && pageList.getRows() != null && !pageList.getRows().isEmpty()) {
                List<Map<String, Object>> resultRows = new ArrayList<>();
                
                for (Order order : pageList.getRows()) {
                    // 转换为Map以便添加额外信息
                    Map<String, Object> orderMap = convertOrderToMap(order);
                    
                    // 添加初始数据信息
                    enrichOrderWithInitialData(orderMap, order);
                    
                    resultRows.add(orderMap);
                }
                
                // 创建新的结果对象
                Map<String, Object> result = new HashMap<>();
                result.put("total", pageList.getTotal());
                result.put("rows", resultRows);
                
                return AjaxResult.me().setResultObj(result);
            }
            
            return AjaxResult.me().setResultObj(pageList);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("获取分页数据失败！" + e.getMessage());
        }
    }


    /**
     * 添加订单
     *
     * @param order
     * @return
     */
    @PostMapping("/addOrder")
    public AjaxResult addOrder(@RequestBody Order order) {
        try {
            Object result = orderService.addOrder(order);
            
            // 将订单加入数据跟踪队列，进行异步数据更新
            Order createdOrder = orderService.loadByOid((String)result);
            orderDataMonitorService.addOrderToMonitor(createdOrder);
            
            return AjaxResult.me().setMessage("下单成功").setResultObj(result);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("下单失败！" + e.getMessage());
        }
    }

    /**
     * 单个接单
     *
     * @param id
     * @return
     */
    @MyPermission(name = "单个接单")
    @PostMapping("/{id}")
    public AjaxResult receivingById(@PathVariable("id") Long id) {
        try {
            orderService.receivingById(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("接单失败！" + e.getMessage());
        }
    }

    /**
     * 批量接单
     *
     * @param ids
     * @return
     */
    @MyPermission(name = "批量接单")
    @PostMapping("/receivingByIds")
    public AjaxResult receivingByIds(@RequestBody List<Long> ids) {
        try {
            orderService.receivingByIds(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("批量接单失败！" + e.getMessage());
        }
    }

    @PostMapping("/receiving")
    public AjaxResult receiving(@RequestBody ReceivingDto receivingDto) {
        try {
            List<Order> list = orderService.receivingByshopId(receivingDto);
            return AjaxResult.me().setMessage("已接单").setResultObj(list);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("批量接单失败！" + e.getMessage());
        }
    }

    /**
     * 查找用户订单
     * @param query
     * @return
     */
    @PostMapping("/uid")
    public AjaxResult loadByUid(@RequestBody OrderQuery query) {
        try {
            PageList<Order> pageList = orderService.pageList(query);
            
            // 处理查询返回结果，添加初始数据信息
            if (pageList != null && pageList.getRows() != null && !pageList.getRows().isEmpty()) {
                List<Map<String, Object>> resultRows = new ArrayList<>();
                
                for (Order order : pageList.getRows()) {
                    // 转换为Map以便添加额外信息
                    Map<String, Object> orderMap = convertOrderToMap(order);
                    
                    // 添加初始数据信息
                    enrichOrderWithInitialData(orderMap, order);
                    
                    resultRows.add(orderMap);
                }
                
                // 创建新的结果对象
                Map<String, Object> result = new HashMap<>();
                result.put("total", pageList.getTotal());
                result.put("rows", resultRows);
                
                return AjaxResult.me().setResultObj(result);
            }
            
            return AjaxResult.me().setResultObj(pageList);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("获取分页数据失败！" + e.getMessage());
        }
    }

    /**
     * 用户退款：先校验状态 是否为0， 只需修改状态；
     */
    @GetMapping("/refund/{oid}")
    public AjaxResult refund(@PathVariable("oid") String oid) {
        try {
            Order order = orderService.loadByOid(oid);
            if (order.getOType() == 1) {
                order.setOType(BaseConstants.Order.STATE_PENDING_REFUND);
                orderService.update(order);
                return AjaxResult.me();
            }
            return AjaxResult.me().setSuccess(false).setMessage("该订单不符合退款条件");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("获取一个失败！" + e.getMessage());
        }
    }

    /**
     * 完成度刷新
     *
     * @param ShopId
     * @return
     */
    @GetMapping("/refreshByFllow/{ShopId}")
    public AjaxResult RefreshByFllow(@PathVariable("ShopId") Long ShopId) {
        try {

            return orderService.refreshByFllow(ShopId);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("刷新失败！" + e.getMessage());
        }
    }

    @GetMapping("/refreshByBaseByf/{ShopId}")
    public AjaxResult RefreshByBaseByf(@PathVariable("ShopId") Long ShopId) {
        try {

            return orderService.refreshByBase(ShopId);

        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("刷新失败！" + e.getMessage());
        }
    }
    @GetMapping("/refreshByBaseByc/{ShopId}")
    public AjaxResult RefreshByBaseByc(@PathVariable("ShopId") Long ShopId) {
        try {

            return orderService.refreshByBaseByc(ShopId);

        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("刷新失败！" + e.getMessage());
        }
    }

    @GetMapping("/refreshByBaseByTall/{ShopId}")
    public AjaxResult RefreshByBaseByTall(@PathVariable("ShopId") Long ShopId) {
        try {

            return orderService.refreshByBaseByTall(ShopId);

        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("刷新失败！" + e.getMessage());
        }
    }

    @GetMapping("/refreshByBaseByg/{ShopId}")
    public AjaxResult RefreshByBaseByg(@PathVariable("ShopId") Long ShopId) {
        try {

            return orderService.refreshByBaseByg(ShopId);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("刷新失败！" + e.getMessage());
        }
    }

    @GetMapping("/refreshByBaseByp/{ShopId}")
    public AjaxResult RefreshByBaseByp(@PathVariable("ShopId") Long ShopId) {
        try {

            return orderService.refreshByBaseByp(ShopId);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("刷新失败！" + e.getMessage());
        }
    }

    @GetMapping("/refreshByBaseByt/{ShopId}")
    public AjaxResult RefreshByBaseByt(@PathVariable("ShopId") Long ShopId) {
        try {

            return orderService.refreshByBaseByt(ShopId);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("刷新失败！" + e.getMessage());
        }
    }

    @GetMapping("/refreshByConmentGoos/{ShopId}")
    public AjaxResult refreshByConmentGoos(@PathVariable("ShopId") Long ShopId) {
        try {

            return orderService.refreshByConmentGoos(ShopId);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("刷新失败！" + e.getMessage());
        }
    }




    @GetMapping("/refreshByVideo/{ShopId}")
    public AjaxResult RefreshByVideo(@PathVariable("ShopId") Long ShopId) {
        try {
            return orderService.refreshByVideo(ShopId);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("刷新失败！" + e.getMessage());
        }
    }

//    @GetMapping("/processing/{ShopId}")
//    public AjaxResult Processing(@PathVariable("ShopId") Long ShopId) {
//        try {
//            return orderService.processing(ShopId);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return AjaxResult.me().setSuccess(false).setMessage("订单待处理失败!" + e.getMessage());
//        }
//    }







    /**
     * 后台商家退款
     *
     * @param refundDto
     * @return
     */
    @MyPermission(name = "商家退款")
    @PostMapping("/merchantRefund")
    public AjaxResult merchantRefund(@RequestBody RefundDto refundDto) {
        try {
            return orderService.merchantRefund(refundDto);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("退款失败" + e.getMessage());
        }
    }

    /**
     * 商家批量退款
     * @param orderList
     * @return
     */
    @MyPermission(name = "商家批量退款")
    @PostMapping("/bulkRefund")
    public AjaxResult bulkRefund(@RequestBody List<Order> orderList) {
        try {
            return orderService.bulkRefund(orderList);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("批量退款失败" + e.getMessage());
        }
    }

    /**
     * 获取批量退款订单
     * @param ids
     * @return
     */
    @MyPermission(name = "获取批量退款订单")
    @PostMapping("/loadByIds")
    public AjaxResult loadRefundOrderByIds(@RequestBody List<Long> ids) {
        try {
            List<Order> refundOrders = orderService.loadRefundOrderByIds(ids);
            
            if (refundOrders != null && !refundOrders.isEmpty()) {
                List<Map<String, Object>> resultList = new ArrayList<>();
                
                for (Order order : refundOrders) {
                    // 转换为Map以便添加额外信息
                    Map<String, Object> orderMap = convertOrderToMap(order);
                    
                    // 添加初始数据信息
                    enrichOrderWithInitialData(orderMap, order);
                    
                    resultList.add(orderMap);
                }
                
                return AjaxResult.me().setResultObj(resultList);
            }
            
            return AjaxResult.me().setResultObj(refundOrders);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("批量接单失败！" + e.getMessage());
        }
    }


    @PostMapping("/SelectByIds")
    public AjaxResult SelectByIds(@RequestBody List<Long> ids) {
        try {
            List<Copy> orders = orderService.SelectByIds(ids);
            return AjaxResult.me().setResultObj(orders);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("批量复制失败！" + e.getMessage());
        }
    }

    @GetMapping("/SelectById/{id}")
    public AjaxResult SelectById(@PathVariable("id") Long id) {
        try {
            Copy copy = orderService.SelectById(id);
            ArrayList<Copy> copies = new ArrayList<>();
            copies.add(copy);
            return AjaxResult.me().setResultObj(copies);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("复制失败！" + e.getMessage());
        }
    }


    @PostMapping("/addLotOrder")
    public AjaxResult addLotOrder(@RequestBody List<Order> orders) {
        try {
            Boolean result = orderService.addLotOrder(orders);
            if (Boolean.TRUE.equals(result)) {
                // 将每个订单添加到监控队列中
                for (Order order : orders) {
                    // 这里需要先获取已创建的订单对象
                    // 注意：我们假设订单的OId已经在addLotOrder中设置
                    Order createdOrder = orderService.loadById(order.getId());
                    if (createdOrder != null) {
                        orderDataMonitorService.addOrderToMonitor(createdOrder);
                    }
                }
                return AjaxResult.me().setMessage("批量下单成功");
            } else {
                return AjaxResult.me().setSuccess(false).setMessage("批量下单失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("批量下单失败！" + e.getMessage());
        }
    }

    @PostMapping("/newOrder")
    public AjaxResult newOrder(@RequestBody NewOrderDto dto){
        try {

            return  orderService.newOrder(dto);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("更新失败！" + e.getMessage());
        }
    }

    @GetMapping("/GetOrderTotal/{shopId}")
    public AjaxResult GetOrderTotal(@PathVariable("shopId") Long shopid){
        try {

            return  orderService.getTotal(shopid);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("更新失败！" + e.getMessage());
        }
    }

    @GetMapping("/complete/{id}")
    public AjaxResult completeByOrder(@PathVariable("id") Long id) {
        try {
            orderService.completeByOrder(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("手动完成失败！" + e.getMessage());
        }
    }

    @GetMapping("/completeOid/{oid}")
    public AjaxResult completeOid(@PathVariable("oid") String oid) {
        try {
            Order order = orderService.loadByOid(oid);
            if(order.getOType()!=BaseConstants.Order.STATE_ONGOING){
                return AjaxResult.me().setSuccess(false).setMessage("请校验正在进行中的订单");
            }
            
            // 转换为Map并添加初始数据信息
            Map<String, Object> orderMap = convertOrderToMap(order);
            enrichOrderWithInitialData(orderMap, order);
            
            List<Map<String, Object>> list = new ArrayList<>();
            list.add(orderMap);
            
            return AjaxResult.me().setResultObj(list);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("获取订单失败！" + e.getMessage());
        }
    }

    @GetMapping("/verification/{oid}")
    public AjaxResult verification(@PathVariable("oid") String oid){
        try {
            Order order = orderService.loadByOid(oid);
            if (order == null) {
                return AjaxResult.me().setSuccess(false).setMessage("订单不存在");
            }
            
            // 实时从微博获取最新数据
            Map<String, Object> liveData = new HashMap<>();
            Integer goodsType = order.getGoods() != null ? order.getGoods().getType() : 0;
            
            if(goodsType == 1){
                String fllow = Utils.getFllow();
                String subValue = Utils.getSubValue(fllow);
                FllowDto fllowDto = new FllowDto();
                fllowDto.setUrl(order.getUrl());
                fllowDto.setSub(subValue);
                Integer followdata = Utils.getFollowdata(fllowDto);
                liveData.put("initialFollow", followdata);
                liveData.put("dataType", "关注");
            } else if(goodsType == 6){
                AjaxResult ajaxResult = VideoUtils.ToolUtils(order.getUrl());
                String videoData = (String) ajaxResult.getResultObj();
                Integer integer = VideoUtils.convertToWan(videoData);
                liveData.put("initialVideo", integer);
                liveData.put("dataType", "视频播放");
            } else {
                AjaxResult ajaxResult = Utils.ToolUtils(order.getUrl());
                ArrayList<Integer> arrayList = (ArrayList<Integer>) ajaxResult.getResultObj();
                liveData.put("initialForward", arrayList.get(0));
                liveData.put("initialComment", arrayList.get(1));
                liveData.put("initialLike", arrayList.get(2));
                liveData.put("dataType", "转评赞");
            }
            
            // 转换为标准格式
            Map<String, Object> orderMap = convertOrderToMap(order);
            enrichOrderWithInitialData(orderMap, order);
            
            // 添加实时数据
            orderMap.put("liveData", liveData);
            orderMap.put("message", "实时爬取URL数据成功");
            
            return AjaxResult.me().setMessage("爬取URL数据成功").setResultObj(orderMap);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("爬取URL数据失败！" + e.getMessage());
        }
    }

//    @GetMapping("/refreshByOid/{oid}")
//    public AjaxResult refreshByOid(@PathVariable("oid") String oid) {
//        try {
//            Order order = orderService.loadByOid(oid);
//            if(order.getOType()!=BaseConstants.Order.STATE_ONGOING){
//                return AjaxResult.me().setSuccess(false).setMessage("请刷新正在进行中的订单");
//            }
//            List<Order> list = new ArrayList<>();
//            list.add(order);
//            AjaxResult refresh = orderService.refresh(list);
//            return refresh;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return AjaxResult.me().setSuccess(false).setMessage("获取订单失败！" + e.getMessage());
//        }
//    }

    @PostMapping("/testUrl")
    public AjaxResult testUrl(String url) {
        try {
            AjaxResult ajaxResult = VideoUtils.ToolUtils(url);
            System.out.println(ajaxResult);
            Integer sv = VideoUtils.convertToWan((String) ajaxResult.getResultObj());
            HashMap<String, Integer> map = new HashMap<>();
            map.put("视频播放",sv);
            return AjaxResult.me().setResultObj(map);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("获取订单失败！" + e.getMessage());
        }
    }

    @PostMapping("/TestUrl")
    public AjaxResult TestUrl(@RequestBody Url url){
        try {

            AjaxResult ajaxResult = Utils.ToolUtils(url.getUrl());
            return ajaxResult;
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("测试链接失败！" + e.getMessage());
        }
    }

    @PostMapping("/deleteBytime")
    public AjaxResult deleteBytime(@RequestBody DeleteDto dto) {
        try {
            orderService.deleteBytime(dto);

            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除失败！" + e.getMessage());
        }
    }

    @PostMapping("/addorderByunified")
    public AjaxResult addorderByunified(@RequestBody UnifiedDto dto) {
        try {
            Boolean result = orderService.addorderByunified(dto);
            
            // 获取生成的订单，将它们添加到监控队列
            // 假设统一订单会生成多个子订单，我们需要找到它们并添加到监控队列
            OrderQuery query = new OrderQuery();
            query.setUrl(dto.getUrl()); // 使用URL字段搜索
            query.setUid(dto.getUId()); // 使用uid字段 
            
            // 查询最近创建的相关订单
            PageList<Order> pageList = orderService.pageList(query);
            if (pageList != null && pageList.getRows() != null) {
                for (Order order : pageList.getRows()) {
                    // 只处理刚创建的待处理订单
                    if (order.getOType() == BaseConstants.Order.STATE_PENDORDER) {
                        orderDataMonitorService.addOrderToMonitor(order);
                    }
                }
            }
            
            return AjaxResult.me().setMessage("下单成功");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("下单失败！" + e.getMessage());
        }
    }

    @GetMapping("/countOderByUser/{uid}")
    public AjaxResult countOderByUser(@PathVariable("uid") Long uid) {
        try {
            UserOrderStatusCounts count = orderService.countOderByUser(uid);
            HashMap<String, Integer> map = new HashMap<>();
            map.put("待接单",count.getPendingCount());
            map.put("进行中",count.getShippedCount());
            map.put("已完成",count.getDeliveredCount());
            map.put("订单取消",count.getCancelledCount());
            map.put("退款中",count.getRefundCount());
            return AjaxResult.me().setResultObj(map);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("获取订单失败！" + e.getMessage());
        }
    }

    /**
     * 查看订单初始数据爬取状态
     * 
     * @param oid 订单ID
     * @return 订单的初始数据状态
     */
    @GetMapping("/orderInitialData/{oid}")
    public AjaxResult getOrderInitialData(@PathVariable("oid") String oid) {
        try {
            Order order = orderService.loadByOid(oid);
            if (order == null) {
                return AjaxResult.me().setSuccess(false).setMessage("订单不存在");
            }
            
            // 创建一个返回对象，包含订单的初始数据
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("orderId", order.getId());
            dataMap.put("orderOid", order.getOId());
            dataMap.put("url", order.getUrl());
            dataMap.put("goodsType", order.getGoods() != null ? order.getGoods().getType() : null);
            dataMap.put("orderStatus", order.getOType());
            
            // 添加不同类型订单的初始数据
            Integer goodsType = order.getGoods() != null ? order.getGoods().getType() : 0;
            
            if (goodsType == 1) {
                // 关注类型
                dataMap.put("initialFollow", order.getSFollow());
                dataMap.put("dataComplete", order.getSFollow() != null && order.getSFollow() > 0);
            } else if (goodsType == 6) {
                // 视频类型
                dataMap.put("initialVideo", order.getSVideo());
                dataMap.put("dataComplete", order.getSVideo() != null && order.getSVideo() > 0);
            } else if (goodsType == 5) {
                // 类型5特殊处理
                dataMap.put("dataComplete", true);
            } else if (goodsType == 10) {
                // 内评赞类型
                dataMap.put("initialCommentLike", order.getSGood());
                dataMap.put("dataComplete", order.getSGood() != null && order.getSGood() > 0);
            } else {
                // 其他类型（转发、评论、点赞等）
                dataMap.put("initialForward", order.getSForward());
                dataMap.put("initialComment", order.getSComment());
                dataMap.put("initialLike", order.getSGood());
                dataMap.put("dataComplete", 
                    order.getSForward() != null && order.getSForward() > 0 &&
                    order.getSComment() != null && order.getSComment() > 0 &&
                    order.getSGood() != null && order.getSGood() > 0);
            }
            
            // 如果数据未爬取成功，可以提供重新爬取的提示
            if (!(Boolean)dataMap.get("dataComplete")) {
                dataMap.put("message", "数据爬取中，请稍后刷新查看");
            } else {
                dataMap.put("message", "初始数据爬取完成");
            }
            
            return AjaxResult.me().setResultObj(dataMap);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("获取订单初始数据失败！" + e.getMessage());
        }
    }
    
    /**
     * 手动触发订单初始数据爬取（针对管理员）
     * 
     * @param oid 订单ID
     * @return 操作结果
     */
    @PostMapping("/triggerOrderDataFetch/{oid}")
    @MyPermission(name = "触发订单数据爬取")
    public AjaxResult triggerOrderDataFetch(@PathVariable("oid") String oid) {
        try {
            Order order = orderService.loadByOid(oid);
            if (order == null) {
                return AjaxResult.me().setSuccess(false).setMessage("订单不存在");
            }
            
            // 将订单添加到监控队列最前端（高优先级处理）
            orderDataMonitorService.addOrderToMonitorWithHighPriority(order);
            
            return AjaxResult.me().setMessage("已触发订单数据爬取，请稍后刷新查看结果");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("触发订单数据爬取失败！" + e.getMessage());
        }
    }

    /**
     * 批量查询多个订单的初始数据状态（用于管理员批量查看）
     * 
     * @param query 订单查询条件
     * @return 订单初始数据列表
     */
    @PostMapping("/batchOrderInitialData")
    @MyPermission(name = "批量查询订单初始数据")
    public AjaxResult batchGetOrderInitialData(@RequestBody OrderQuery query) {
        try {
            // 限制每页大小，避免查询过多数据
            if (query.getPageSize() > 100) {
                query.setPageSize(100L);
            }
            
            PageList<Order> pageList = orderService.pageList(query);
            if (pageList == null || pageList.getRows() == null || pageList.getRows().isEmpty()) {
                return AjaxResult.me().setMessage("未找到符合条件的订单");
            }
            
            List<Map<String, Object>> resultList = new ArrayList<>();
            
            for (Order order : pageList.getRows()) {
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("orderId", order.getId());
                dataMap.put("orderOid", order.getOId());
                dataMap.put("url", order.getUrl());
                dataMap.put("count", order.getCount());
                dataMap.put("createTime", order.getCreateTime());
                dataMap.put("goodsType", order.getGoods() != null ? order.getGoods().getType() : null);
                dataMap.put("goodsName", order.getGoods() != null ? order.getGoods().getName() : null);
                dataMap.put("orderStatus", order.getOType());
                
                // 添加不同类型订单的初始数据
                Integer goodsType = order.getGoods() != null ? order.getGoods().getType() : 0;
                
                if (goodsType == 1) {
                    // 关注类型
                    dataMap.put("initialFollow", order.getSFollow());
                    dataMap.put("dataComplete", order.getSFollow() != null);
                    dataMap.put("dataType", "关注");
                } else if (goodsType == 6) {
                    // 视频类型
                    dataMap.put("initialVideo", order.getSVideo());
                    dataMap.put("dataComplete", order.getSVideo() != null);
                    dataMap.put("dataType", "视频播放");
                } else if (goodsType == 5) {
                    // 类型5特殊处理
                    dataMap.put("dataComplete", true);
                    dataMap.put("dataType", "特殊类型");
                } else if (goodsType == 10) {
                    // 内评赞类型
                    dataMap.put("initialCommentLike", order.getSGood());
                    dataMap.put("dataComplete", order.getSGood() != null);
                    dataMap.put("dataType", "内评赞");
                } else {
                    // 其他类型（转发、评论、点赞等）
                    dataMap.put("initialForward", order.getSForward());
                    dataMap.put("initialComment", order.getSComment());
                    dataMap.put("initialLike", order.getSGood());
                    dataMap.put("dataComplete", 
                        order.getSForward() != null && 
                        order.getSComment() != null && 
                        order.getSGood() != null);
                    dataMap.put("dataType", "转评赞");
                }
                
                resultList.add(dataMap);
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("total", pageList.getTotal());
            result.put("rows", resultList);
            
            return AjaxResult.me().setResultObj(result);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("批量获取订单初始数据失败！" + e.getMessage());
        }
    }

    /**
     * 将Order对象转换为Map
     */
    private Map<String, Object> convertOrderToMap(Order order) {
        Map<String, Object> orderMap = new HashMap<>();
        
        // 复制基本属性
        orderMap.put("id", order.getId());
        orderMap.put("oId", order.getOId());
        orderMap.put("sId", order.getSId());
        orderMap.put("ShopId", order.getShopId());
        orderMap.put("uId", order.getUId());
        orderMap.put("url", order.getUrl());
        orderMap.put("count", order.getCount());
        orderMap.put("surplus", order.getSurplus());
        orderMap.put("finalPrice", order.getFinalPrice());
        orderMap.put("oType", order.getOType());
        orderMap.put("createTime", order.getCreateTime());
        orderMap.put("Completion", order.getCompletion());
        orderMap.put("refundNumber", order.getRefundNumber());
        orderMap.put("sType", order.getSType());
        
        // 复制关联对象
        if (order.getGoods() != null) {
            Map<String, Object> goodsMap = new HashMap<>();
            goodsMap.put("id", order.getGoods().getId());
            goodsMap.put("name", order.getGoods().getName());
            goodsMap.put("type", order.getGoods().getType());
            goodsMap.put("price", order.getGoods().getPrice());
            goodsMap.put("btype", order.getGoods().getBtype());
            orderMap.put("goods", goodsMap);
        }
        
        if (order.getUser() != null) {
            Map<String, Object> userMap = new HashMap<>();
            userMap.put("id", order.getUser().getId());
            userMap.put("username", order.getUser().getUsername());
            orderMap.put("user", userMap);
        }
        
        if (order.getManager() != null) {
            Map<String, Object> managerMap = new HashMap<>();
            managerMap.put("id", order.getManager().getId());
            managerMap.put("username", order.getManager().getUsername());
            orderMap.put("manager", managerMap);
        }
        
        return orderMap;
    }
    
    /**
     * 为订单添加初始数据信息
     */
    private void enrichOrderWithInitialData(Map<String, Object> orderMap, Order order) {
        // 创建初始数据信息部分
        Map<String, Object> initialDataMap = new HashMap<>();
        
        // 添加不同类型订单的初始数据
        Integer goodsType = order.getGoods() != null ? order.getGoods().getType() : 0;
        
        if (goodsType == 1) {
            // 关注类型
            initialDataMap.put("initialFollow", order.getSFollow());
            initialDataMap.put("dataComplete", order.getSFollow() != null);
            initialDataMap.put("dataType", "关注");
            initialDataMap.put("initialDataDesc", "关注数: " + (order.getSFollow() != null ? order.getSFollow() : "正在获取"));
        } else if (goodsType == 6) {
            // 视频类型
            initialDataMap.put("initialVideo", order.getSVideo());
            initialDataMap.put("dataComplete", order.getSVideo() != null);
            initialDataMap.put("dataType", "视频播放");
            initialDataMap.put("initialDataDesc", "播放数: " + (order.getSVideo() != null ? order.getSVideo() : "正在获取"));
        } else if (goodsType == 5) {
            // 类型5特殊处理
            initialDataMap.put("dataComplete", true);
            initialDataMap.put("dataType", "特殊类型");
            initialDataMap.put("initialDataDesc", "无需获取初始数据");
        } else if (goodsType == 10) {
            // 内评赞类型
            initialDataMap.put("initialCommentLike", order.getSGood());
            initialDataMap.put("dataComplete", order.getSGood() != null);
            initialDataMap.put("dataType", "内评赞");
            initialDataMap.put("initialDataDesc", "点赞数: " + (order.getSGood() != null ? order.getSGood() : "正在获取"));
        } else {
            // 其他类型（转发、评论、点赞等）
            initialDataMap.put("initialForward", order.getSForward());
            initialDataMap.put("initialComment", order.getSComment());
            initialDataMap.put("initialLike", order.getSGood());
            initialDataMap.put("dataComplete", 
                order.getSForward() != null && 
                order.getSComment() != null && 
                order.getSGood() != null);
            initialDataMap.put("dataType", "转评赞");
            
            StringBuilder sb = new StringBuilder();
            sb.append("转发: ").append(order.getSForward() != null ? order.getSForward() : "正在获取");
            sb.append(", 评论: ").append(order.getSComment() != null ? order.getSComment() : "正在获取");
            sb.append(", 点赞: ").append(order.getSGood() != null ? order.getSGood() : "正在获取");
            initialDataMap.put("initialDataDesc", sb.toString());
        }
        
        // 将初始数据信息添加到订单数据中
        orderMap.put("initialData", initialDataMap);
    }
    
    /**
     * 手动触发订单数据爬取（通过现有的接单接口实现）
     * 
     * @param id 订单ID
     * @return 操作结果
     */
    @GetMapping("/fetchInitialData/{id}")
    public AjaxResult fetchInitialData(@PathVariable("id") Long id) {
        try {
            Order order = orderService.loadById(id);
            if (order == null) {
                return AjaxResult.me().setSuccess(false).setMessage("订单不存在");
            }
            
            // 将订单添加到监控队列最前端（高优先级处理）
            orderDataMonitorService.addOrderToMonitorWithHighPriority(order);
            
            return AjaxResult.me().setMessage("已触发订单数据爬取，请稍后刷新查看结果");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("触发订单数据爬取失败！" + e.getMessage());
        }
    }

}
